<!-- DynamicTabs.vue -->
<template>
    <el-tabs v-model="activeTab" type="border-card" closable @tab-remove="removeTab">
      <el-tab-pane v-for="item in tabs" :key="item.name" :label="item.title" :name="item.name">
        <component :is="item.component"></component>
      </el-tab-pane>
    </el-tabs>
  </template>
  
  <script setup>
  import { ref } from 'vue';
  
  const tabs = ref([]);
  const activeTab = ref('');
  
  async function loadComponent(path) {
    const component = (await import(/* @vite-ignore */ path)).default;
    return component;
  }
  
  // 添加 tab 方法
  const addTab = async ({ name, title, path }) => {
    const exists = tabs.value.some((t) => t.name === name);
    if (!exists) {
      const component = await loadComponent(path);
      tabs.value.push({ name, title, component });
    }
    activeTab.value = name;
  };
  
  // 移除 tab 方法
  const removeTab = (targetName) => {
    const index = tabs.value.findIndex((tab) => tab.name === targetName);
    tabs.value.splice(index, 1);
    if (activeTab.value === targetName) {
      const newTab = tabs.value[index - 1] || tabs.value[0];
      activeTab.value = newTab ? newTab.name : '';
    }
  };
  
  // 暴露方法给父组件调用
  defineExpose({
    addTab,
  });
  </script>